package main

import (
	"fmt"
	"net/http"
)

func SetCookie(w http.ResponseWriter, r *http.Request) {
	var cookie = &http.Cookie{
		Name:  "user",
		Value: "kevin",
	}
	var cookie2 = &http.Cookie{
		Name:  "user2",
		Value: "kevin2",
	}
	var cookie3 = &http.Cookie{
		Name:   "user3",
		Value:  "kevin3",
		MaxAge: 10,
	}
	//通过Header的Set方法设置cookie
	w.Header().Set("Set-Cookie", cookie.String())
	w.Header().Add("Set-Cookie", cookie2.String())
	//通过http的SetCookie方法来设置cookie
	http.SetCookie(w, cookie3)
}

func GetCookie(w http.ResponseWriter, r *http.Request) {
	//通过Cookies获取所有cookie的切片
	cookies := r.Cookies()
	for k, v := range cookies {
		fmt.Printf("%d==>%v\n", k, v)
	}
	//通过Cookie获取某个cookie
	cookie2, _ := r.Cookie("user2")
	fmt.Println(cookie2)
}

func main() {
	http.HandleFunc("/setCookie", SetCookie)
	http.HandleFunc("/getCookie", GetCookie)
	http.ListenAndServe(":8080", nil)
}
